package com.ganzalang.gmallleetcode.linkedlist.easy;

public class ReverseLinkedList {

    public static void main(String[] args) {
        ListNode[] nodes = new ListNode[5];
        nodes[4] = new ListNode(5, null);
        nodes[3] = new ListNode(4, nodes[4]);
        nodes[2] = new ListNode(3, nodes[3]);
        nodes[1] = new ListNode(2, nodes[2]);
        nodes[0] = new ListNode(1, nodes[1]);

        ReverseLinkedList bean = new ReverseLinkedList();
        bean.reverseList(nodes[0]);
    }

    public ListNode reverseList(ListNode head) {
        ListNode node1 = head;
        ListNode node2 = head;

        if (node1 == null || node1.next == null) {
            return head;
        }

        do {
            ListNode next = node2.next;
            node2 = next;
            node2.next = node1;
            node1 = node2;
        } while (node2.next != null);

        return node1;
    }

    /**
     * Definition
     */
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
